var selectedRow='';
var selectedRecordRow='';
var s_operType = 'revoke';
var isInit = true;
$(function () {
    newCheck.initByName('_reason');
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openEditPage('info');
        },
        'click .isvInfoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openCommonIsvPage(row.isvPid, 'doc');
        },
    }
    initTextSearch("#pDeptName",basePath + 'basicDoctorInfo/getPDeptList?t='+ (new Date()).getTime()+'&name=',['deptCode','deptName'],{'deptCode':'科室编码','deptName':'科室名称'},'deptCode','deptName',true,selectPDeptValue,pDeptChange);
    initTextSearchWithParam("#cDeptName",basePath + 'basicDoctorInfo/getCDeptList?t='+ (new Date()).getTime(),['deptCode','deptName'],{'deptCode':'科室编码','deptName':'科室名称'},'deptCode','deptName',true,selectCDeptValue,cDeptChange,getPDeptCode);
    initTextSearch("#orgName",basePath + 'basicDoctorInfo/getOrgList?t='+ (new Date()).getTime()+'&name=',['orgCode','orgName'],{'orgCode':'机构编码','orgName':'机构名称'},'orgCode','orgName',true,selectOrgValue,orgChange);
    initTextSearch("#isvPidName",basePath + 'basicDoctorInfo/getIsvList?t='+ (new Date()).getTime()+'&name=',['isvPid','isvName'],{'isvPid':'服务商Pid','isvName':'服务商名称'},'isvPid','isvName',true,selectIsvValue,isvChange);
});

function getPDeptCode(){
    var pDeptCode = $('#pDeptCode').val();
    return {
        t: new Date().getTime(),
        name: $('#cDeptName').val(),
        parentCode: pDeptCode
    };
}

// dataTable
$('#dataTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    var index = $element[0].rowIndex - 1;
    $('#dataTable').bootstrapTable('uncheckAll');
    $('#dataTable').bootstrapTable('check', index);
    $('#dataTable .success').removeClass('success');//去除之前选中的行的，选中样式
    $element.addClass('success');//添加当前选中的 success样式用于区别
    selectedRow = row;
    doRefreshLog();
});

//右边选中事件
$("#dataTable2").on("click-row.bs.table",function(e,row,ele){
    $("#recordTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRecordRow = row;
});

function formatPublishStatus(value, row, index){
    return convertMapCodeText(publishStatusMap,value);
}

function formatDataStatus(value, row, index){
    return convertMapCodeText(dataStatusMap,value);
}

function formatCheckType(value, row, index){
    return convertMapCodeText(checkTypeMap,value);
}

function formatCheckResultType(value, row, index){
    return convertMapCodeText(checkResultTypeMap,value);
}

function openEditPage(command) {
    if (command != 'add' && command != 'edit'&&command != 'info') return;
    var id="";
    if (command != 'add') {
        if (!selectedRow || selectedRow.id == '') {
            toastr.error(common_no_choose_msg.format("编辑"));
            return;
        }
        if (command == 'edit' && selectedRow.dataStatus == 'pending_check') {
            toastr.error('待审核的专家无法直接编辑');
            return;
        }
        id=selectedRow.id;
    }
    var tableOptions = $('#dataTable').bootstrapTable('getOptions', null);
    window.location.href = basePath + "basicDoctorInfo/editBasicDoctorInfoPage?type=" + command + "&id=" + id + '&t=' + new Date().getTime() + '&' + $('#searchForm').serialize() + '&pageNo=' + tableOptions.pageNumber + '&pageSize=' + tableOptions.pageSize;
}

function doRefresh() {
    var docName = $("#docName").val();
    var isvPid = $("#isvPid").val();
    var status = $("#status").val();
    var dataStatus = $("#dataStatus").val();
    var docMediLevel = $("#docMediLevel").val();
    var pDeptCode = $("#pDeptCode").val();
    var cDeptCode = $("#cDeptCode").val();
    var orgCode = $("#orgCode").val();
    var isMerge = $("#isMerge").val();
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'basicDoctorInfo/pageFindBasicDoctorInfoData?t='+new Date().getTime(),
        docName: docName,
        isvPid: isvPid,
        status: status,
        dataStatus: dataStatus,
        docMediLevel: docMediLevel,
        pDeptCode: pDeptCode,
        cDeptCode: cDeptCode,
        isMerge: isMerge,
        orgCode: orgCode
    });
}

function getParams(params) {
    var docName = $("#docName").val();
    var isvPid = $("#isvPid").val();
    var status = $("#status").val();
    var dataStatus = $("#dataStatus").val();
    var docMediLevel = $("#docMediLevel").val();
    var pDeptCode = $("#pDeptCode").val();
    var cDeptCode = $("#cDeptCode").val();
    var orgCode = $("#orgCode").val();
    var isMerge = $("#isMerge").val();
    // var pageSize = searchInfo.pageSize ? searchInfo.pageSize : params.pageSize;
    // var pageNo = searchInfo.pageNo ? searchInfo.pageNo : params.pageNo;
    var pageSize = params.pageSize;
    var pageNo = params.pageNumber;
    if (isInit) {
        isInit = false;
        pageSize = searchInfo.pageSize ? searchInfo.pageSize : params.pageSize;
        pageNo = searchInfo.pageNo ? searchInfo.pageNo : params.pageNumber;
    }
    return {
        docName: docName,
        isvPid: isvPid,
        status: status,
        dataStatus: dataStatus,
        docMediLevel: docMediLevel,
        pDeptCode: pDeptCode,
        cDeptCode: cDeptCode,
        isMerge: isMerge,
        orgCode: orgCode,
        pageSize : pageSize,
        pageNo : pageNo
    };
}

function doRefreshLog() {
    var docCode = selectedRow.docCode;
    $('#dataTable2').bootstrapTable('refresh', {
        url: basePath + 'basicDoctorInfo/pageFindBasicDocInfoCheckLogData?t='+new Date().getTime(),
        query: {
            bizCode : docCode
        }
    });
}

function pDeptChange() {
    //清空值
    $('#pDeptCode').val("");
    //修改一级时，清空二级
    $('#cDeptCode').val("");
    $('#cDeptName').val("");
}

function selectPDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#pDeptCode').val(data.deptCode);
        //修改一级时，清空二级
        $('#cDeptCode').val("");
        $('#cDeptName').val("");
    }
}

function cDeptChange() {
    //清空值
    $('#cDeptCode').val("");
}

function selectCDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#cDeptCode').val(data.deptCode);
    }
}

function orgChange() {
    //清空值
    $('#orgCode').val("");
}

function selectOrgValue(data) {
    //联动赋值
    if (data && data.orgCode && data.orgCode != '') {
        $('#orgCode').val(data.orgCode);
    }
}

function isvChange() {
    //清空值
    $('#isvPid').val("");
}

function selectIsvValue(data) {
    //联动赋值
    if (data && data.isvPid && data.isvPid != '') {
        $('#isvPid').val(data.isvPid);
    }
}

function doCommit() {
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("提交发布"));
        return;
    }
    if (selectedRow.dataStatus == 'pending_check') {
        toastr.error('待审核的专家无法提交发布');
        return;
    }
    if (selectedRow.dataStatus == 'check_pass' || selectedRow.status == 'check_fail') {
        toastr.error('该专家没有修改，无需发布');
        return;
    }
    var str = '确认提交发布吗？';
    swalToastr('提交发布', str, 'warning', doCommitDoc, '确认提交');
}

function doCommitDoc() {
    var postData = {
        id : selectedRow.id,
        docCode : selectedRow.docCode,
        docMergeCode : selectedRow.docMergeCode
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'basicDoctorInfo/commitDoc?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error('提交失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('提交成功，等待管理员审核！');
            doRefresh();
            return;
        },
    });
}

function getReasonData() {
    var checks=$('input[name="_reason"]:checked');
    var str = '';
    checks.each(function(idx,element){
        str += $(element).val() + ',';
    });
    var reason = $.trim($('#reason').val());
    str += reason;
    if (!reason || reason == '') {
        str = str.length > 0 ? str.substring(0, str.length - 1) : '';
    }
    return str;
}

function checkDocRevoke() {
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("撤销"));
        return;
    }
    if (selectedRow.status != 'publish') {
        toastr.error("未发布的专家不能撤销");
        return;
    }
    if (selectedRow.dataStatus == 'pending_check') {
        toastr.error("待审核的专家不能撤销");
        return;
    }
    showSetReasonPage('revoke');
}

function doRevoke() {
    var reason = getReasonData();
    if (!reason || reason == '') {
        toastr.error('撤销原因不能为空');
        return;
    }
    var postData = {
        id : selectedRow.id,
        docCode : selectedRow.docCode,
        reason : reason
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'basicDoctorInfo/revokeDoc?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error('撤销失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('成功撤销');
            closeSetReasonPage();
            doRefresh();
            return;
        },
    });
}

function showSetReasonPage(type) {
    s_operType = type;
    if (type == 'delete') {
        $('#_modelTitle').html('删除');
    } else {
        $('#_modelTitle').html('撤销发布');
    }
    $('#setReasonPage').modal('show');
    // $('#setReasonPage').show();
}

function closeSetReasonPage() {
    $('#setReasonPage').modal('hide');
    // $('#setReasonPage').hide();
    $("input[type=checkbox][name=_reason]").removeAttr("checked");
    $('#reason').val('');
}

function doSaveReason() {
    if (s_operType == 'delete') {
        var strHtml = '是否删除专家？该操作会变更数据！';
        swalToastr('', strHtml, 'warning', deleteDoc);
    } else if (s_operType == 'revoke') {
        doRevoke();
    } else {
        toastr.error(common_system_error);
    }
}

function doExport() {
    $('#searchForm').attr("action",basePath+"basicDoctorInfo/exportDocDataExcel?t=" + new Date().getTime());
    $('#searchForm').submit();
}

function checkDocDelete() {
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("删除"));
        return;
    }
    if (selectedRow.status == 'publish') {
        toastr.error("已发布的专家不能直接删除");
        return;
    }
    if (selectedRow.dataStatus == 'pending_check') {
        toastr.error("待审核的专家不能删除");
        return;
    }
    var postData = {
        id : selectedRow.id,
        docCode : selectedRow.docCode
    };
    $.ajax({
        type: 'post',
        url: basePath + 'basicDoctorInfo/checkDocDelete',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if (!data) {
                toastr.error('校验删除失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            if (data.errorCode == 'HAS_REF') {
                toastr.error('该专家已关联其他业务，无法删除');
            } else {
                showSetReasonPage('delete');
            }
            return;
        },
    });
}

function deleteDoc() {
    var reason = getReasonData();
    if (!reason || reason == '') {
        toastr.error('删除原因不能为空');
        return;
    }
    var postData = {
        id : selectedRow.id,
        reason : reason
    };
    $.ajax({
        type: 'post',
        url: basePath + 'basicDoctorInfo/deleteBasicDoctorInfo?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data && data.isSuccess){
                toastr.success('删除成功');
                closeSetReasonPage();
                doRefresh();
            }else if(data&&!data.isSuccess){
                toastr.error(data.errorDesc);
            }else{
                toastr.error('删除失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}